package com.skzh.web.controller.uavTask;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.skzh.common.core.controller.BaseController;
import com.skzh.common.core.domain.AjaxResult;
import com.skzh.common.core.page.TableDataInfo;
import com.skzh.common.utils.DateUtils;
import com.skzh.equipment.domain.Dock;
import com.skzh.equipment.service.IDockService;
import com.skzh.flightplans.domain.FlightPlans;
import com.skzh.flightplans.service.IFlightPlansService;
import com.skzh.framework.config.ServerConfig;
import com.skzh.uavTask.domain.*;
import com.skzh.uavTask.service.ITaskInfoService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.validation.Valid;
import java.util.*;

@RestController
@RequestMapping("/uavTask/task")
public class TaskInfoController extends BaseController {
    @Autowired
    private ITaskInfoService taskService;

    @Autowired
    private ObjectMapper objectMapper;



    @Autowired
    private IDockService dockService;


    @Autowired
    private IFlightPlansService flightPlansService;


    /**
     * 查询航线列表列表
     */
    @ApiOperation(value = "查询航线列表列表")
    @PreAuthorize("@ss.hasPermi('uavTask:task:list')")
    @GetMapping("/Planlist")
    public TableDataInfo Planlist(FlightPlans flightPlans) {

        List<FlightPlans> list = flightPlansService.selectFlightPlansList(flightPlans);
        return getDataTable(list);
    }


    /**
     * 查询机场基本信息列表
     */
    @ApiOperation(value = "查询机场基本信息列表")
    @PreAuthorize("@ss.hasPermi('uavTask:task:list')")
    @GetMapping("/dockList" )
    public TableDataInfo docklist(Dock dock) {

        List<Dock> list = dockService.selectDockList(dock);
        return getDataTable(list);
    }


    /**
     * 获取任务列表
     */
    @PreAuthorize("@ss.hasPermi('uavTask:task:list')")
    @GetMapping("/list")
    public TableDataInfo list(TaskInfo task) {
        startPage();
        List<TaskInfo> list = taskService.selectTaskList(task);
        // 让 PageHelper 自动处理分页
        return getDataTable(list);
    }

    /**
     * 获取任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('uavTask:task:query')")
    @GetMapping("/{taskId}")
    public AjaxResult getInfo(@PathVariable Long taskId) {
        return success(taskService.selectTaskById(taskId));
    }

    /**
     * 添加任务执行记录
     */
    @PreAuthorize("@ss.hasPermi('uavTask:task:add')")
    @PostMapping("/execRecord")
    public AjaxResult addExecRecord(@RequestBody TaskExecRecord record) {
        return toAjax(taskService.insertTaskExecRecord(record));
    }

    /**
     * 获取任务执行记录
     */
    @PreAuthorize("@ss.hasPermi('uavTask:task:query')")
    @GetMapping("/execRecord/{taskId}")
    public TableDataInfo getExecRecords(@PathVariable Long taskId) {
        startPage();

        List<TaskExecRecord> list2 = taskService.selectTaskExecRecordList(taskId);


        return getDataTable(list2);
    }

    /**
     * 开始执行任务
     */
    @PreAuthorize("@ss.hasPermi('uavTask:task:start')")
    @PutMapping("/start/{taskId}")
    public AjaxResult startTask(@PathVariable Long taskId) {
        // 开始执行任务时自动添加一条执行记录
        TaskExecRecord record = new TaskExecRecord();
        record.setTaskId(taskId);
        record.setStatus("0"); // 0-开始执行
        taskService.insertTaskExecRecord(record);
        return toAjax(taskService.startTask(taskId));
    }

    /**
     * 新增任务
     */
    @PreAuthorize("@ss.hasPermi('uavTask:task:add')")
    @PostMapping
    public AjaxResult add(@RequestBody TaskInfo task) {
        if (task.getExecType().equals("0")) {
            // 立即执行时，添加当前时间并设置状态为执行中
            List<String> currentTime = new ArrayList<>();
            currentTime.add(DateUtils.getTime());
            task.setExecTime(objectMapper.valueToTree(currentTime));
            task.setStatus("1");  // 设置为执行中状态
        } else {
            // 定时执行或周期执行时，设置状态为待执行
            task.setStatus("0");
        }

        // 先创建任务
        int rows = taskService.insertTask(task);

        // 如果是立即执行的任务，在获取到taskId后添加执行记录
        if (rows > 0 && task.getExecType().equals("0")) {
            TaskExecRecord record = new TaskExecRecord();
            record.setTaskId(task.getTaskId());  // 现在有了taskId
            record.setStatus("0"); // 0-开始执行
            taskService.insertTaskExecRecord(record);
        }

        return toAjax(rows);
    }

    /**
     * 修改任务
     */
    @PreAuthorize("@ss.hasPermi('uavTask:task:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody TaskInfo task) {
        return toAjax(taskService.updateTask(task));
    }

    /**
     * 删除任务
     */
    @PreAuthorize("@ss.hasPermi('uavTask:task:remove')")
    @DeleteMapping("/{taskIds}")
    public AjaxResult remove(@PathVariable Long[] taskIds) {
        return toAjax(taskService.deleteTaskByIds(taskIds));
    }

    /**
     * 暂停任务
     */
    @PreAuthorize("@ss.hasPermi('uavTask:task:pause')")
    @PutMapping("/pause/{taskId}")
    public AjaxResult pause(@PathVariable Long taskId) {
        // 暂停任务时自动添加一条执行记录
        TaskExecRecord record = new TaskExecRecord();
        record.setTaskId(taskId);
        record.setStatus("3"); // 3-任务暂停
        taskService.insertTaskExecRecord(record);
        return toAjax(taskService.pauseTask(taskId));
    }

    /**
     * 终止任务
     */
    @PreAuthorize("@ss.hasPermi('uavTask:task:stop')")
    @PutMapping("/stop/{taskId}")
    public AjaxResult stop(@PathVariable Long taskId) {
        // 终止任务时自动添加一条执行记录
        TaskExecRecord record = new TaskExecRecord();
        record.setTaskId(taskId);
        record.setStatus("4"); // 4-任务终止
        taskService.insertTaskExecRecord(record);
        return toAjax(taskService.stopTask(taskId));
    }

    /**
     * 根据年月获取任务
     */
    @GetMapping("/select/monthly")
    public AjaxResult getMonthlySchedule(@Valid TaskScheduleQueryDTO queryDTO) {
        List<TaskScheduleVO> schedule = taskService.getMonthlySchedule(queryDTO.getYearMonth());

        if (schedule != null) {
            List<TaskScheduleVO> toAdd = new ArrayList<>();
            Iterator<TaskScheduleVO> iterator = schedule.iterator();

            while (iterator.hasNext()) {

                TaskScheduleVO taskScheduleVO = iterator.next();
                String execTimes = taskScheduleVO.getExecTimes();
                ObjectMapper mapper = new ObjectMapper();
                String[] split = null;
                try {
                    split = mapper.readValue(execTimes, String[].class);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                if (split.length > 1) {
                    iterator.remove();
                    for (int i = 0; i < split.length; i++) {
                        TaskScheduleVO taskScheduleVO1 = new TaskScheduleVO();
                        taskScheduleVO1.setTaskId(taskScheduleVO.getTaskId());
                        taskScheduleVO1.setTaskName(taskScheduleVO.getTaskName());
                        taskScheduleVO1.setTaskDate(taskScheduleVO.getTaskDate());
                        taskScheduleVO1.setExecTimes(split[i]);
                        String s = taskScheduleVO.getTaskDate() + " " + split[i];
                        Date date = DateUtils.parseDate(s);
                        taskScheduleVO1.setExecTime(date);
                        toAdd.add(taskScheduleVO1);
                    }
                } else {
                    String replace = taskScheduleVO.getExecTimes().replace("[", "").replace("]", "").replace("\"", "");
                    String s = taskScheduleVO.getTaskDate() + " " + replace;
                    Date date = DateUtils.parseDate(s);
                    taskScheduleVO.setExecTime(date);

                }
            }
            schedule.addAll(toAdd);
        }
        return AjaxResult.success(schedule);
    }

    /**
     * 根据机场id获取任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('uavTask:task:query2')")
    @GetMapping("/query")
    public TableDataInfo getInfoByDockId(TaskInfo2 taskInfo2) {
        startPage();
        List<TaskInfo2> taskInfos = taskService.selectTaskByDockId(taskInfo2);
//        for (TaskInfo2 taskInfo : taskInfos) {
//            System.out.println("-----------------------");
//            System.out.println(taskInfo.getExecTime());
//        }
        return getDataTable(taskInfos);
    }
}
